<template>
  <div class="work-order-container">
    <h2>工单生成与推送</h2>
    <!-- 工单生成表单 -->
    <el-form :model="form" label-width="120px" class="work-order-form" @submit.native.prevent>
      <el-form-item label="设备健康度">
        <el-input-number v-model="form.healthScore" :min="0" :max="100" @change="autoGenerateWorkOrder" />
        <span style="color: #999; margin-left: 10px;">分（低于40分自动生成工单）</span>
      </el-form-item>
      <el-form-item label="关键参数">
        <el-select v-model="form.keyParam" placeholder="请选择参数" @change="autoGenerateWorkOrder">
          <el-option label="温度" value="温度" />
          <el-option label="压力" value="压力" />
          <el-option label="电流" value="电流" />
        </el-select>
        <el-input-number v-model="form.keyParamValue" :min="0" :max="200" style="margin-left: 10px;" @change="autoGenerateWorkOrder" />
        <span style="color: #999; margin-left: 10px;">（如温度超上限20%自动生成工单）</span>
      </el-form-item>
      <el-form-item label="故障定位">
        <el-select v-model="form.faultLocation" placeholder="请选择">
          <el-option label="X轴伺服电机" value="X轴伺服电机" />
          <el-option label="Y轴减速箱" value="Y轴减速箱" />
          <el-option label="主轴轴承" value="主轴轴承" />
        </el-select>
      </el-form-item>
      <el-form-item label="维修步骤">
        <el-select v-model="form.maintenanceGuide" placeholder="加载标准作业指导书">
          <el-option label="X轴伺服电机更换作业指导书" value="X轴伺服电机更换作业指导书" />
          <el-option label="Y轴减速箱检修作业指导书" value="Y轴减速箱检修作业指导书" />
          <el-option label="主轴轴承更换作业指导书" value="主轴轴承更换作业指导书" />
        </el-select>
      </el-form-item>
      <el-form-item label="备件清单">
        <el-select v-model="form.spareParts" multiple placeholder="自动关联库存">
          <el-option label="轴承型号6205" value="轴承型号6205" />
          <el-option label="伺服电机" value="伺服电机" />
          <el-option label="减速箱油封" value="减速箱油封" />
        </el-select>
      </el-form-item>
      <el-form-item label="紧急程度">
        <el-radio-group v-model="form.urgency">
          <el-radio label="高">高</el-radio>
          <el-radio label="中">中</el-radio>
          <el-radio label="低">低</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="通知配置">
        <el-checkbox-group v-model="form.notifyMethods">
          <el-checkbox label="APP弹窗" />
          <el-checkbox label="短信" />
          <el-checkbox label="邮件" />
        </el-checkbox-group>
      </el-form-item>
      <el-form-item label="联系方式">
        <el-input v-model="form.contact" placeholder="请输入运维人员联系方式" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleManualGenerate">手动生成工单</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 待办任务列表 -->
    <h3 style="margin-top: 40px;">待办任务列表</h3>
    <el-table
      :data="sortedWorkOrders"
      style="width: 100%;"
      :row-class-name="tableRowClassName"
      height="400"
    >
      <el-table-column prop="id" label="序号" width="60" />
      <el-table-column prop="createdAt" label="生成时间" width="160" />
      <el-table-column prop="faultLocation" label="故障定位" width="120" />
      <el-table-column prop="maintenanceGuide" label="维修步骤" width="180" />
      <el-table-column prop="spareParts" label="备件清单" width="160">
        <template slot-scope="scope">
          <span v-for="(part, idx) in scope.row.spareParts" :key="idx">{{ part }}<span v-if="idx < scope.row.spareParts.length-1">, </span></span>
        </template>
      </el-table-column>
      <el-table-column prop="urgency" label="紧急程度" width="80" />
      <el-table-column prop="notifyMethods" label="通知方式" width="120">
        <template slot-scope="scope">
          <span v-for="(method, idx) in scope.row.notifyMethods" :key="idx">{{ method }}<span v-if="idx < scope.row.notifyMethods.length-1">, </span></span>
        </template>
      </el-table-column>
      <el-table-column prop="contact" label="联系方式" width="120" />
      <el-table-column prop="status" label="状态" width="100" />
      <el-table-column prop="upgrade" label="升级提醒" width="100">
        <template slot-scope="scope">
          <span v-if="scope.row.upgrade" style="color: red;">已升级</span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="100">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="markAsDone(scope.row)">完成</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
export default {
  name: 'WorkOrderGenerationAndPush',
  data() {
    return {
      form: {
        healthScore: 100,
        keyParam: '',
        keyParamValue: 0,
        faultLocation: '',
        maintenanceGuide: '',
        spareParts: [],
        urgency: '中',
        notifyMethods: [],
        contact: ''
      },
      workOrders: [],
      inventory: ['轴承型号6205', '伺服电机', '减速箱油封'],
      guides: {
        'X轴伺服电机': 'X轴伺服电机更换作业指导书',
        'Y轴减速箱': 'Y轴减速箱检修作业指导书',
        '主轴轴承': '主轴轴承更换作业指导书'
      },
      locationParts: {
        'X轴伺服电机': ['伺服电机'],
        'Y轴减速箱': ['减速箱油封'],
        '主轴轴承': ['轴承型号6205']
      },
      timer: null
    }
  },
  computed: {
    sortedWorkOrders() {
      // 紧急程度排序，高>中>低，未完成优先
      const urgencyMap = { '高': 3, '中': 2, '低': 1 }
      return this.workOrders
        .filter(w => w.status !== '已完成')
        .sort((a, b) => {
          if (urgencyMap[b.urgency] !== urgencyMap[a.urgency]) {
            return urgencyMap[b.urgency] - urgencyMap[a.urgency]
          }
          return new Date(b.createdAt) - new Date(a.createdAt)
        })
    }
  },
  created() {
    this.loadWorkOrders()
    this.startUpgradeTimer()
  },
  beforeDestroy() {
    clearInterval(this.timer)
  },
  methods: {
    autoGenerateWorkOrder() {
      // 设备健康度<40 或 温度超上限20%（假设上限100）
      if (
        this.form.healthScore < 40 ||
        (this.form.keyParam === '温度' && this.form.keyParamValue > 120)
      ) {
        // 自动填充故障定位、维修步骤、备件清单
        if (!this.form.faultLocation) {
          this.form.faultLocation = 'X轴伺服电机'
        }
        if (!this.form.maintenanceGuide) {
          this.form.maintenanceGuide = this.guides[this.form.faultLocation]
        }
        if (!this.form.spareParts.length) {
          this.form.spareParts = this.locationParts[this.form.faultLocation] || []
        }
        this.$message.success('检测到异常，已自动生成工单信息，请确认后提交')
      }
    },
    handleManualGenerate() {
      // 校验
      if (!this.form.faultLocation || !this.form.maintenanceGuide || !this.form.spareParts.length || !this.form.notifyMethods.length || !this.form.contact) {
        this.$message.error('请完善工单信息和通知配置')
        return
      }
      const newOrder = {
        id: this.workOrders.length + 1,
        createdAt: this.formatDate(new Date()),
        ...this.form,
        status: '待处理',
        upgrade: false,
        timeout: Date.now() + 1000 * 60 * 30 // 30分钟后超时升级
      }
      this.workOrders.push(newOrder)
      this.saveWorkOrders()
      this.$message.success('工单已生成并推送到待办任务列表')
      this.resetForm()
    },
    resetForm() {
      this.form = {
        healthScore: 100,
        keyParam: '',
        keyParamValue: 0,
        faultLocation: '',
        maintenanceGuide: '',
        spareParts: [],
        urgency: '中',
        notifyMethods: [],
        contact: ''
      }
    },
    saveWorkOrders() {
      localStorage.setItem('workOrders', JSON.stringify(this.workOrders))
    },
    loadWorkOrders() {
      const data = localStorage.getItem('workOrders')
      if (data) {
        this.workOrders = JSON.parse(data)
      }
    },
    markAsDone(row) {
      row.status = '已完成'
      this.saveWorkOrders()
      this.$message.success('工单已完成')
    },
    startUpgradeTimer() {
      this.timer = setInterval(() => {
        const now = Date.now()
        let changed = false
        this.workOrders.forEach(order => {
          if (order.status === '待处理' && !order.upgrade && now > order.timeout) {
            order.upgrade = true
            changed = true
            this.$notify({
              title: '工单超时升级提醒',
              message: `工单[${order.id}]已超时未处理，请尽快处理！`,
              type: 'warning'
            })
          }
        })
        if (changed) this.saveWorkOrders()
      }, 10000) // 每10秒检查一次
    },
    tableRowClassName({ row }) {
      if (row.upgrade) return 'row-upgrade'
      if (row.urgency === '高') return 'row-high'
      return ''
    },
    formatDate(date) {
      const y = date.getFullYear()
      const m = ('0' + (date.getMonth() + 1)).slice(-2)
      const d = ('0' + date.getDate()).slice(-2)
      const h = ('0' + date.getHours()).slice(-2)
      const min = ('0' + date.getMinutes()).slice(-2)
      const s = ('0' + date.getSeconds()).slice(-2)
      return `${y}-${m}-${d} ${h}:${min}:${s}`
    }
  }
}
</script>

<style scoped>
.work-order-container {
  padding: 24px;
  background: #fff;
  min-height: 100vh;
}
.work-order-form {
  max-width: 700px;
  margin-bottom: 30px;
}
.row-upgrade {
  background: #fff2e8 !important;
}
.row-high {
  background: #ffeaea !important;
}
</style>
